package com.awesome.spring.service.impl;

import com.alibaba.fastjson.JSON;
import com.awesome.spring.bean.Order;
import com.awesome.spring.bean.TransactionMessage;
import com.awesome.spring.feign.AccountFeign;
import com.awesome.spring.mapper.OrderMapper;
import com.awesome.spring.mapper.TransactionMessageMapper;
import com.awesome.spring.service.OrderService;
import com.awesome.spring.service.TransactionMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * OrderServiceImpl
 *
 * @author alex
 * @date 2022/07/07
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private TransactionMessageService transactionMessageService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(String userId, int money, boolean rollback) {
        // 1. 保存订单
        String orderCode = UUID.randomUUID().toString();

        Order order = new Order();
        order.setCode(orderCode);
        order.setCount(1);
        order.setUserId(userId);
        order.setMoney(money);
        this.save(order);

        // int a = 1/0 ; // 模拟异常 不发出

        // 2. 保存待发送的消息
        transactionMessageService.saveTransactionMessage("order-topic", JSON.toJSONString(order));

        // 3. 事务提交后消息也会保存


    }
}
